package com.yz.Stack;
import java.util.Scanner;

public class StackDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        //创建出该栈对象
        ArrayStack stack = new ArrayStack(4);
        //定义一个菜单来控制该栈
        boolean flag = true;
        while (flag){
            System.out.println("（show）展示栈中数据");
            System.out.println("（pop）将数据输入栈");
            System.out.println("（push）将数据输出栈");
            System.out.println("（exit）退出");
            System.out.println("请输入你的指令：");
            String next = scanner.next();
            switch (next){
                case "show":
                    stack.show();
                    break;
                case "pop":
                    System.out.println("请输入一个数：");
                    int i = scanner.nextInt();
                    stack.pop(i);
                    break;
                case "push":
                    try {
                        int res = stack.push();
                        System.out.printf("输出数据是…%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case "exit":
                    flag = false;
                    break;
            }
        }
        System.out.println("程序退出！");
    }
}

//定义一个栈
class ArrayStack{
    //占所需要的元素，栈的最大容量，栈的栈顶指针，用数组来模拟栈
    private int Maxsize;
    private int top;
    private int[] array;
    //定义构造方法
    public ArrayStack(int Max){
        this.top = -1;
        this.Maxsize = Max;
        array = new int[Max];
    }

    //判断栈是否为空
    public boolean isNull(){
        return top == -1;
    }

    //判断栈是否为满
    public  boolean inFull(){
        //数组下标从1开始
        return Maxsize-1 == top;
    }

    //将元素入栈
    public void pop(int value){
        if (inFull()){
            System.out.println("栈满！无法压入元素！");
        }
        array[++top] = value;
    }

    //将元素出栈
    public int push(){
        if (isNull()){
            throw new RuntimeException("栈空，无法输出元素！");
        }
        //输出元素从栈顶开始输出元素
        return array[top--];
    }
    //展示栈中元素
    public void show(){
        if (isNull()) {
            System.out.println("该队列是空的，无法展示元素");
        }
        for (int i = top; i>=0; i--) {
            System.out.printf("array[%d] = %d\n", i, array[i]);
        }
    }

}
